/**
 * 连接状态监控服务
 * 监控CTP交易和行情连接状态，检测连接异常并提供通知
 * 当检测到连接断开时，自动触发重连
 */
import { ref, computed } from 'vue'
import { listen } from '@tauri-apps/api/event'
import { autoReconnectService } from '../services/autoReconnectService'

// 连接状态枚举
export const ConnectionStatus = {
  CONNECTED: 'connected',
  DISCONNECTED: 'disconnected',
  CONNECTING: 'connecting',
  RECONNECTING: 'reconnecting'
}

// 全局状态
const mdStatus = ref(ConnectionStatus.DISCONNECTED)
const traderStatus = ref(ConnectionStatus.DISCONNECTED)
const mdSessionId = ref(null)
const traderSessionId = ref(null)
const lastMdDisconnectReason = ref(null)
const lastTraderDisconnectReason = ref(null)
const lastMdDisconnectTime = ref(null)
const lastTraderDisconnectTime = ref(null)
const connectionHistory = ref([])

// 登录成功标记（用于区分登录中和已登录状态）
const mdLoginSucceeded = ref(false)
const traderLoginSucceeded = ref(false)

// 事件监听器列表
const listeners = []

// 初始化标志
let initialized = false
let initPromise = null

// 自动重连配置
const autoReconnectEnabled = ref(true) // 是否启用自动重连
const reconnectAttempts = ref(0) // 重连尝试次数
const maxReconnectAttempts = 999 // 最大重连次数
const reconnectDelay = 3000 // 重连延迟（毫秒）
let reconnectTimer = null // 重连定时器

/**
 * 初始化连接监控
 */
export function useConnectionMonitor() {
  if (!initialized) {
    initialized = true
    initPromise = initializeConnectionMonitor()
  }

  // 计算总体连接状态
  const overallStatus = computed(() => {
    if (mdStatus.value === ConnectionStatus.CONNECTED && 
        traderStatus.value === ConnectionStatus.CONNECTED) {
      return ConnectionStatus.CONNECTED
    }
    if (mdStatus.value === ConnectionStatus.DISCONNECTED && 
        traderStatus.value === ConnectionStatus.DISCONNECTED) {
      return ConnectionStatus.DISCONNECTED
    }
    if (mdStatus.value === ConnectionStatus.CONNECTING || 
        traderStatus.value === ConnectionStatus.CONNECTING) {
      return ConnectionStatus.CONNECTING
    }
    return ConnectionStatus.DISCONNECTED
  })

  // 是否有连接异常
  const hasConnectionIssue = computed(() => {
    return mdStatus.value === ConnectionStatus.DISCONNECTED || 
           traderStatus.value === ConnectionStatus.DISCONNECTED
  })

  /**
   * 添加连接状态变化监听器
   */
  function onConnectionChange(callback) {
    listeners.push(callback)
    return () => {
      const index = listeners.indexOf(callback)
      if (index > -1) {
        listeners.splice(index, 1)
      }
    }
  }

  /**
   * 获取连接状态描述
   */
  function getStatusDescription(type) {
    const status = type === 'md' ? mdStatus.value : traderStatus.value
    const statusMap = {
      [ConnectionStatus.CONNECTED]: '已连接',
      [ConnectionStatus.DISCONNECTED]: '已断开',
      [ConnectionStatus.CONNECTING]: '连接中',
      [ConnectionStatus.RECONNECTING]: '重连中'
    }
    return statusMap[status] || '未知'
  }

  /**
   * 获取最后断线原因
   */
  function getLastDisconnectReason(type) {
    if (type === 'md') {
      return lastMdDisconnectReason.value
    }
    return lastTraderDisconnectReason.value
  }

  /**
   * 获取连接历史记录
   */
  function getConnectionHistory(limit = 10) {
    return connectionHistory.value.slice(0, limit)
  }

  /**
   * 清除连接历史
   */
  function clearConnectionHistory() {
    connectionHistory.value = []
  }

  /**
   * 启用/禁用自动重连
   */
  function setAutoReconnect(enabled) {
    autoReconnectEnabled.value = enabled
    console.log(`🔄 [ConnectionMonitor] 自动重连已${enabled ? '启用' : '禁用'}`)
  }

  /**
   * 手动触发重连
   */
  async function manualReconnect() {
    console.log('🔄 [ConnectionMonitor] 手动触发重连...')
    await attemptReconnect('trader')
  }

  /**
   * 取消重连
   */
  function cancelReconnect() {
    if (reconnectTimer) {
      clearTimeout(reconnectTimer)
      reconnectTimer = null
      console.log('🔄 [ConnectionMonitor] 已取消重连')
    }
    reconnectAttempts.value = 0
  }

  /**
   * 重置登录状态（用于登出或重新登录）
   */
  function resetLoginStatus() {
    mdLoginSucceeded.value = false
    traderLoginSucceeded.value = false
    reconnectAttempts.value = 0
    console.log('🔄 [ConnectionMonitor] 已重置登录状态')
  }

  return {
    // 状态
    mdStatus,
    traderStatus,
    mdSessionId,
    traderSessionId,
    overallStatus,
    hasConnectionIssue,
    lastMdDisconnectReason,
    lastTraderDisconnectReason,
    lastMdDisconnectTime,
    lastTraderDisconnectTime,
    autoReconnectEnabled,
    reconnectAttempts,
    
    // 方法
    onConnectionChange,
    getStatusDescription,
    getLastDisconnectReason,
    getConnectionHistory,
    clearConnectionHistory,
    setAutoReconnect,
    manualReconnect,
    cancelReconnect,
    resetLoginStatus
  }
}

/**
 * 初始化连接监控
 */
async function initializeConnectionMonitor() {
  console.log('🔍 [ConnectionMonitor] 开始初始化连接状态监控...')

  try {
    // 监听连接状态变化事件
    const unlisten = await listen('connection_status_change', (event) => {
      const data = event.payload
      console.log('📡 [ConnectionMonitor] 收到连接状态变化事件:', data)

      handleConnectionStatusChange(data)
    })

    console.log('✅ [ConnectionMonitor] 连接状态监控初始化完成')
    
    // 返回取消监听的函数
    return unlisten
  } catch (error) {
    console.error('❌ [ConnectionMonitor] 初始化失败:', error)
    throw error
  }
}

// 立即初始化监听器，不等待组件挂载
initializeConnectionMonitor().catch(err => {
  console.error('❌ [ConnectionMonitor] 自动初始化失败:', err)
})

/**
 * 处理连接状态变化
 */
function handleConnectionStatusChange(data) {
  console.log('📡 [ConnectionMonitor] 处理连接状态变化:', data)
  const { type, status, reason_code, reason_text, session_id, timestamp } = data

  // 添加到历史记录
  connectionHistory.value.unshift({
    type,
    status,
    reason_code,
    reason_text,
    session_id,
    timestamp: timestamp || new Date().toISOString()
  })

  // 限制历史记录数量
  if (connectionHistory.value.length > 100) {
    connectionHistory.value = connectionHistory.value.slice(0, 100)
  }

  // 更新状态
  if (type === 'md') {
    // 处理行情连接状态
    if (status === 'login_success' || status === ConnectionStatus.CONNECTED) {
      mdStatus.value = ConnectionStatus.CONNECTED
      mdSessionId.value = session_id
      mdLoginSucceeded.value = true // 标记登录成功
      console.log('✅ [ConnectionMonitor] 行情连接成功')
      lastMdDisconnectReason.value = null
    } else if (status === 'login_failed') {
      mdStatus.value = ConnectionStatus.DISCONNECTED
      mdLoginSucceeded.value = false // 登录失败，不触发重连
      lastMdDisconnectReason.value = {
        text: reason_text || '登录失败'
      }
      console.warn('⚠️ [ConnectionMonitor] 行情登录失败:', reason_text)
    } else if (status === ConnectionStatus.DISCONNECTED) {
      mdStatus.value = status
      mdSessionId.value = session_id
      lastMdDisconnectReason.value = {
        code: reason_code,
        text: reason_text
      }
      lastMdDisconnectTime.value = timestamp || new Date().toISOString()
      console.warn('⚠️ [ConnectionMonitor] 行情连接断开:', reason_text)
      
      // 只有在已登录成功后的断线才触发重连
      if (mdLoginSucceeded.value && autoReconnectEnabled.value) {
        console.log('🔄 [ConnectionMonitor] 行情已登录后断线，准备重连...')
        // 注：行情重连逻辑可以在这里添加
      }
    } else {
      mdStatus.value = status
      mdSessionId.value = session_id
    }
  } else if (type === 'trader') {
    // 处理交易连接状态
    if (status === 'login_success' || status === ConnectionStatus.CONNECTED) {
      traderStatus.value = ConnectionStatus.CONNECTED
      traderSessionId.value = session_id
      traderLoginSucceeded.value = true // 标记登录成功
      console.log('✅ [ConnectionMonitor] 交易连接成功')
      lastTraderDisconnectReason.value = null
    } else if (status === 'login_failed') {
      traderStatus.value = ConnectionStatus.DISCONNECTED
      traderLoginSucceeded.value = false // 登录失败，不触发重连
      lastTraderDisconnectReason.value = {
        text: reason_text || '登录失败'
      }
      console.warn('⚠️ [ConnectionMonitor] 交易登录失败（不触发重连）:', reason_text)
    } else if (status === ConnectionStatus.DISCONNECTED) {
      traderStatus.value = status
      traderSessionId.value = session_id
      lastTraderDisconnectReason.value = {
        code: reason_code,
        text: reason_text
      }
      lastTraderDisconnectTime.value = timestamp || new Date().toISOString()
      console.warn('⚠️ [ConnectionMonitor] 交易连接断开:', reason_text)
      
      // 只有在已登录成功后的断线才触发重连
      if (traderLoginSucceeded.value && autoReconnectEnabled.value) {
        console.log('🔄 [ConnectionMonitor] 交易已登录后断线，触发自动重连...')
        scheduleReconnect('trader')
      } else {
        console.log('ℹ️ [ConnectionMonitor] 登录过程中的断线，不触发重连')
      }
    } else {
      traderStatus.value = status
      traderSessionId.value = session_id
    }
  }

  // 通知所有监听器
  notifyListeners({
    type,
    status,
    reason_code,
    reason_text,
    session_id,
    timestamp
  })
}

/**
 * 通知所有监听器
 */
function notifyListeners(data) {
  listeners.forEach(callback => {
    try {
      callback(data)
    } catch (error) {
      console.error('❌ [ConnectionMonitor] 监听器回调错误:', error)
    }
  })
}

/**
 * 获取断线原因的友好描述
 */
export function getDisconnectReasonDescription(reasonCode) {
  const reasonMap = {
    0x1001: '网络读取失败',
    0x1002: '网络写入失败',
    0x2001: '接收心跳超时',
    0x2002: '发送心跳失败',
    0x2003: '收到错误报文'
  }
  return reasonMap[reasonCode] || `未知错误 (${reasonCode})`
}

/**
 * 安排重连
 */
function scheduleReconnect(type) {
  // 如果已经有重连计划，先取消
  if (reconnectTimer) {
    clearTimeout(reconnectTimer)
    reconnectTimer = null
  }

  // 检查是否超过最大重连次数
  if (reconnectAttempts.value >= maxReconnectAttempts) {
    console.error(`❌ [ConnectionMonitor] ${type}重连失败，已达到最大重连次数(${maxReconnectAttempts})`)
    reconnectAttempts.value = 0
    return
  }

  reconnectAttempts.value++
  console.log(`🔄 [ConnectionMonitor] 安排${type}重连，第${reconnectAttempts.value}次尝试，${reconnectDelay}ms后执行...`)

  // 更新状态为重连中
  if (type === 'trader') {
    traderStatus.value = ConnectionStatus.RECONNECTING
  } else if (type === 'md') {
    mdStatus.value = ConnectionStatus.RECONNECTING
  }

  // 延迟执行重连
  reconnectTimer = setTimeout(() => {
    attemptReconnect(type)
  }, reconnectDelay)
}

/**
 * 尝试重连
 */
async function attemptReconnect(type) {
  console.log(`🔄 [ConnectionMonitor] 开始执行${type}重连...`)

  try {
    if (type === 'trader') {
      // 尝试重连交易API
      const success = await autoReconnectService.ensureTraderConnection()
      
      if (success) {
        console.log('✅ [ConnectionMonitor] 交易连接重连成功')
        reconnectAttempts.value = 0
        traderStatus.value = ConnectionStatus.CONNECTED
        
        // 通知监听器重连成功
        notifyListeners({
          type: 'trader',
          status: 'reconnect_success',
          timestamp: new Date().toISOString()
        })
      } else {
        console.warn(`⚠️ [ConnectionMonitor] 交易连接重连失败，第${reconnectAttempts.value}次尝试`)
        
        // 如果还没达到最大次数，继续尝试
        if (reconnectAttempts.value < maxReconnectAttempts) {
          scheduleReconnect(type)
        } else {
          console.error('❌ [ConnectionMonitor] 交易连接重连失败，已达到最大重连次数')
          traderStatus.value = ConnectionStatus.DISCONNECTED
          reconnectAttempts.value = 0
          
          // 通知监听器重连失败
          notifyListeners({
            type: 'trader',
            status: 'reconnect_failed',
            reason_text: '达到最大重连次数',
            timestamp: new Date().toISOString()
          })
        }
      }
    }
    // TODO: 可以在这里添加行情API的重连逻辑
  } catch (error) {
    console.error(`❌ [ConnectionMonitor] ${type}重连异常:`, error)
    
    // 重连异常，继续尝试
    if (reconnectAttempts.value < maxReconnectAttempts) {
      scheduleReconnect(type)
    } else {
      if (type === 'trader') {
        traderStatus.value = ConnectionStatus.DISCONNECTED
      }
      reconnectAttempts.value = 0
    }
  }
}
